from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect
from django.conf import settings
from web import models
import datetime


class Tracer(object):
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):
        """查找session中user_id是否存在，如果不存在返回0代表未登录，如果user_id存在则代表已登录"""
        # 封装对象，可以不封装直接request.user=user_obj
        request.tracer = Tracer()

        user_id = request.session.get('user_id', 0)
        user_obj = models.UserInfo.objects.filter(id=user_id).first()
        request.tracer.user = user_obj

        """
        白名单
        1. 获取当用户访问的URL
        2. 检查URL是否在白名单中，如果再则可以继续向后访问，如果不在则进行判断是否已登录
        """
        # 如果当前访问的url在白名单中则返回空(代表继续走下去)
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return
        # 如果未登录返回首页
        if not request.tracer.user:
            return redirect('index')

        # 登录成功后获取价格策略
        _object = models.Transaction.objects.filter(user=user_obj, status=2).order_by('-id').first()

        # 判断拿到的交易记录是否过期
        # 获取当前时间
        current_datetime = datetime.datetime.now()
        # 判断过期
        if _object.end_datetime and _object.end_datetime < current_datetime:  # 过期
            _object = models.Transaction.objects.filter(user=user_obj, status=2).order_by('id').first()

        request.tracer.price_policy = _object.price_policy

    def process_view(self, request, view, args, kwargs):

        if not request.path_info.startswith('/manage/'):
            return

        # 拿到manage/后的项目id
        project_id = kwargs.get('project_id')

        # 判断当前访问的id是否是我创建的项目id
        project_object = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        # 如果是就让他通过
        if project_object:
            request.tracer.project = project_object
            return

        # 判断当前访问的id是否是我参与的项目id
        join_project_object = models.ProjectUser.objects.filter(user=request.tracer.user, project_id=project_id).first()
        # 如果是就让他通过
        if join_project_object:
            request.tracer.project = join_project_object.project
            return

        return redirect('project_list')
